<template>
  <div class="ke-detail-banner">
    <div class="left">
      <video-player
        class="video-player vjs-custom-skin"
        ref="videoPlayer"
        :playsinline="true"
        :options="playerOptions"
      />
    </div>
    <div class="right">
      <div class="title">vue源码解读</div>
      <div class="chatContent">
        <div class="content-wrapper">
          <div v-for="(item, index) in chatMsgList" :key="index">
            <div class="mine talk" v-if="item.id === userId">
              <div class="nickName">{{item.nickName}}</div>
              <div class="avitor-mine">
                <img :src="item.avatar" class="avatar" />
              </div>
              <div class="text">{{item.chatMsg}}</div>
            </div>
            <div class="rabit talk" v-else>
              <div class="nickName">{{item.nickName}}</div>
              <div class="avitor avitor-rabit">
                <img :src="item.avatar" class="avatar" />
              </div>
              <div class="text">{{item.chatMsg}}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="inp">
        <input type="text" ref="inp" @keydown.enter="sendChatMsg" />
        <button class="send" @click="sendChatMsg">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ke-detail-banner',
  components: {
    keVideo: () => import('../ke-video')
  },
  props: {
    sourceList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: 'video/mp4',
            src: 'http://localhost:9090/movies/freeCourse/1-2 准备工作.mp4'
          }
        ],
        poster: require('../../assets/images/login-banner.jpg'), //你的封面地址
        // width: document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true //全屏按钮
        }
      },
      websock: null,
      chatMsgList: []
    }
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player
    },
    userId() {
      return localStorage.getItem('ke_id')
    }
  },
  mounted() {
    this.$bus.on('changeCourse', index => {
      this.playerOptions.sources[0].src = this.sourceList[index].courseURI
    })
    this.initWebSocket()
  },
  methods: {
    initWebSocket() {
      //初始化weosocket
      const wsuri = 'ws://127.0.0.1:3000/chat'
      this.websock = new WebSocket(wsuri)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen(chatMsg) {
      console.log('连接建立成功')
      //连接建立之后执行send方法发送数据
      let actions = {
        id: localStorage.getItem('ke_id'),
        chatMsg: chatMsg
      }
      this.websocketsend(JSON.stringify(actions))
    },
    websocketonerror() {
      console.log('连接建立失败')
      //连接建立失败重连
      this.initWebSocket()
    },
    websocketonmessage(e) {
      console.log('接收到数据')
      if (e.data === '[object Event]') {
        return
      }
      const chatData = JSON.parse(e.data)
      this.chatMsgList.push(chatData)
    },
    websocketsend(data) {
      console.log('数据发送')
      // 校验是否有不良言论
      if (data.search('hello') > -1) {
        this.$message({
          type: 'warning',
          message: '请注意你的言辞，不能发出不良言论'
        })
        return
      }
      //数据发送
      this.websock.send(data)
    },
    websocketclose(e) {
      //关闭
      console.log('断开连接', e)
    },
    sendChatMsg() {
      if (this.$refs.inp.value == '' || this.$refs.inp.value === null) {
        this.$message({
          type: 'warning',
          message: '发送内容不能为空'
        })
        return
      }
      const chatMsg = this.$refs.inp.value
      this.$refs.inp.value = null
      this.websocketonopen(chatMsg)
    }
  },
  destroyed() {
    this.websock.close() //离开路由之后断开websocket连接
  }
}
</script>

<style lang="stylus" scoped>
.ke-detail-banner {
  display: flex;
  flex-direction: row;
  width: 1200px;
  height: 615px;
  margin: 10px auto 10px;

  .left {
    flex: 2.5;
    background-color: skyblue;

    /deep/.video-player {
      // position absolute
      width: 100%;
      height: 100%;
      display: block;

      .video-js {
        height: 100%;
      }

      .vjs-poster {
        background-size: 100% 100%;
      }
    }

    /deep/.vjs-big-play-button {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 50%;
      transform: translatex(-50%);
    }
  }

  .right {
    position: relative;
    flex: 1;
    background-color: #eeeeee;
    box-sizing: border-box;
    overflow: hidden;
    border-top: 1px solid #eeeeee;
    // border-left 1px solid #eeeeee
    border-bottom: 1px solid #eeeeee;

    .title {
      position: absolute;
      top: 0;
      width: 100%;
      text-align: center;
      height: 40px;
      line-height: 40px;
      background: grey;
      color: #fff;
      border-bottom: 1px solid #eee;
    }

    .chatContent {
      position: absolute;
      top: 40px;
      left: 0;
      right: 0;
      bottom: 40px;
      overflow-y: scroll; /* 竖向滚动条 */
      scrollbar-face-color: #D4D4D4; /* 滚动条滑块颜色 */
      scrollbar-hightlight-color: #ffffff; /* 滚动条3D界面的亮边颜色 */
      scrollbar-shadow-color: #919192; /* 滚动条3D界面的暗边颜色 */
      scrollbar-3dlight-color: #ffffff; /* 滚动条亮边框颜色 */
      scrollbar-arrow-color: #919192; /* 箭头颜色 */
      scrollbar-track-color: #ffffff; /* 滚动条底色 */
      scrollbar-darkshadow-color: #ffffff;

      .content-wrapper {
        position: absolute;
        width: 100%;

        .talk {
          position: relative;
          width: 100%;
          vertical-align: middle;
          line-height: 30px;
          padding: 5px 0;
          display: inline-block;
          margin-top: 20px;
        }

        .rabit {
          text-align: left;
          padding: 5px 0;

          .text {
            float: left;
            max-width: 230px;
            word-wrap: break-word;
          }

          .nickName {
            position: absolute;
            top: -20px;
            left: 30px;
            font-size: 12px;
            color: #999999;
          }
        }

        .mine {
          text-align: right;
          vertical-align: middle;
          padding: 5px 0;

          .text {
            float: right;
            max-width: 230px;
            word-wrap: break-word;
            background-color: greenyellow;
          }

          .nickName {
            position: absolute;
            top: -20px;
            right: 30px;
            font-size: 12px;
            color: #999999;
          }
        }

        .text {
          background-color: #fff;
          padding: 0 10px;
          border-radius: 5px;
        }

        .mine div, .rabit div {
          display: inline-block;
        }

        .avitor-rabit {
          float: left;
          background-size: 100% 100%;
        }

        .avitor-mine {
          float: right;
          background-size: 100% 100%;
        }

        .avatar {
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }
      }
    }

    .inp {
      position: absolute;
      bottom: 0;
      height: 40px;
      background: #dddddd;
      left: 0;
      right: 0;

      input {
        position: absolute;
        left: 8px;
        top: 50%;
        transform: translateY(-50%);
        padding-left: 5px;
        width: 75%;
        border-radius: 5px;
        outline: none;
        border: none;
        height: 60%;
      }

      button {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        border: none;
        outline: none;
        height: 30px;
        width: 60px;
        background-color: rgb(35, 184, 255);
        border-radius: 8px;
        color: #ffffff;
        cursor: pointer;
      }
    }
  }
}
</style>
